import useUserStore from '@/store/modules/user';
import type { RouteObject } from 'react-router-dom'; 
import routeComponents from '@/router/modules'
import basicRoute from '@/router/index'
import type { MenuRoute } from '@/router/types';
import type { RouterData } from '@/api/menu/getRouters'
import type { RouterInfoMeta } from '@/store/modules/currentPage'
import RenderPage from './RenderPage'
import { cloneDeep, isArray } from 'lodash';

const getPath = (path: string) => {
  if(path.startsWith('/')) return path.slice(1)
  return path
}

export const getInitUser = async ():Promise<boolean> => {
  if (['/login', '/register'].includes(window.location.pathname)) return false;

  const info = await useUserStore.getState().getInfo();
  if (!info) {
    window.location.href = '/login';
    return false
  }
  return true
};

export const transRouteTree = (data: RouterData[]): RouteObject[] => {
  const loopRoutersData = (r: RouterData[], parentsInfo: RouterInfoMeta[] = [], parentsPath = '') => {
    return r.map(e => {
      const currPath = getPath(e.path)
      const fullPath = `${parentsPath}/${currPath}`
      const stack: RouterInfoMeta[] = [
        ...parentsInfo, 
        { href: currPath, title: e.meta.title, link: fullPath }
      ]
      const data: RouteObject = {
        path: currPath,
      }
      if(e.component === 'Layout') {
        data.element = routeComponents['React_Layout']
      } else if (e.component === 'ParentView') {
        data.element = routeComponents['React_ParentView']
      } else if (e.component === 'InnerLink') {
        data.element = routeComponents['React_InnerLink']
      } else {
        if(routeComponents[e.name]) {
          data.element = <RenderPage stack={stack} element={routeComponents[e.name]} path={fullPath} routerMeta={e} key={e.name}/>
        } else {
          data.element = <RenderPage stack={stack} element={routeComponents['React_Blank']} path={fullPath} routerMeta={e} key={e.name} />
        }
      }
      if(isArray(e.children)){
        data.children = loopRoutersData(e.children, stack, fullPath)
      }
      return data
    })
  }
  return loopRoutersData(data, [])
}

export const joinRoutes = (data: RouteObject[] = []) => {
  const routes = cloneDeep(basicRoute)
  routes[2].children = [...routes[2].children, ...data, {path: '*', element: routeComponents['React_NoMatch']}]
  return routes
}

export const getMenuTree = (data: RouterData[]): MenuRoute => {
  const basic = {
    path: '/',
    routes: []
  }

  const readLineMenu = (item: RouterData[] = [], parentsPath?:string) => {
    const child = item.map(e => {
      if(e.hidden) {
        return null
      }
      const currPath = `${parentsPath ? parentsPath : ''}/${getPath(e.path)}`
      const data: MenuRoute['routes'][0] = {
        name: e.meta.title,
        path: currPath
      }
      if(e.meta.link) {
        data.path = e.meta.link
      } 
      if(isArray(e.children)){
        data.routes = readLineMenu(e.children, currPath)
      }
      return data
    }).filter(e => !!e)
    return child
  }

  const routers = readLineMenu(data)
  // {name: '首页', path: '/'}
  return {...basic, routes: [...routers]}
}